package com.zs.backend.modules.certificate.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zs.backend.modules.certificate.dto.UserCertificateDTO;
import com.zs.backend.modules.certificate.model.UserCertificate;
import com.zs.backend.common.api.CommonPage;
import com.zs.backend.common.api.CommonResult;
import com.zs.backend.modules.certificate.service.UserCertificateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

/**
 * <p>
 * 证书表 前端控制器
 * </p>
 *
 * @author zs
 * @since 2024-03-18
 */
@RestController
@Api(tags = "注册类、非注册类证书管理")
@RequestMapping("/certificate")
public class UserCertificateController {

    @Autowired
    private UserCertificateService userCertificateService;

    @ApiOperation("注册类、非注册类证书列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<UserCertificateDTO>> list(
        @ApiParam(value = "公司名称",name = "companyName")
        @RequestParam(value = "companyName", required = false) String companyName,

        @ApiParam(value = "收证人", name = "acceptCertificateUserName")
        @RequestParam(value = "acceptCertificateUserName", required = false) String acceptCertificateUserName,

        @ApiParam(value = "职称年份-开始(yyyy-MM-dd)", name = "startTitleTime")
        @RequestParam(value = "startTitleTime", required = false)  @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTitleTime,

        @ApiParam(value = "职称年份-结束(yyyy-MM-dd)", name = "endTitleTime")
        @RequestParam(value = "endTitleTime", required = false)  @DateTimeFormat(pattern = "yyyy-MM-dd")  Date endTitleTime,

        @ApiParam(value = "人才电话", name = "personnelTel")
        @RequestParam(value = "personnelTel", required = false) String personnelTel,

        @ApiParam(value = "职称专业", name = "titleMajor")
        @RequestParam(value = "titleMajor", required = false) String titleMajor,

        @ApiParam(value = "证书类型", name = "certificateTypeName")
        @RequestParam(value = "certificateTypeName", required = false) String certificateTypeName,

        @ApiParam(value = "毕业专业", name = "graduationMajor")
        @RequestParam(value = "graduationMajor", required = false) String graduationMajor,

        @ApiParam(value = "毕业年份-开始(yyyy-MM-dd)", name = "startGraduationTime")
        @RequestParam(value = "startGraduationTime", required = false)   @DateTimeFormat(pattern = "yyyy-MM-dd") Date startGraduationTime,

        @ApiParam(value = "毕业年份-结束(yyyy-MM-dd)", name = "endGraduationTime")
        @RequestParam(value = "endGraduationTime", required = false)   @DateTimeFormat(pattern = "yyyy-MM-dd") Date endGraduationTime,

        @ApiParam(value = "学历（1：专科，2：本科 ，3：硕士）", name = "qualification")
        @RequestParam(value = "qualification", required = false) String qualification,

        @ApiParam(value = "电子、纸质（1：电子，2：纸质）", name = "category")
        @RequestParam(value = "category", required = false) String category,

        @ApiParam(value = "身份证号", name = "idCard")
        @RequestParam(value = "idCard", required = false) String idCard,

        @ApiParam(value = "证书归属地", name = "certificateBelongingPlace")
        @RequestParam(value = "certificateBelongingPlace", required = false) String certificateBelongingPlace,

        @ApiParam(value = "证书归属地 code", name = "placeCode")
        @RequestParam(value = "placeCode", required = false) String placeCode,

        @ApiParam(value = "限制地区", name = "restrictedAreas")
        @RequestParam(value = "restrictedAreas", required = false) String restrictedAreas,

        @ApiParam(value = "限制地区(多个)", name = "restrictedAreass")
        @RequestParam(value = "restrictedAreass", required = false) String restrictedAreass,

        @ApiParam(value = "职称专业模糊查询", name = "likeTitleMajor")
        @RequestParam(value = "likeTitleMajor", required = false) String likeTitleMajor,

        @ApiParam(value = "职称编号", name = "titleNumber")
        @RequestParam(value = "titleNumber", required = false) String titleNumber,

        @ApiParam(value = "创建时间-开始（yyyy-MM-dd）", name = "startCreateTime")
        @RequestParam(value = "startCreateTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startCreateTime,

        @ApiParam(value = "创建时间-结束（yyyy-MM-dd）", name = "endCreateTime")
        @RequestParam(value = "endCreateTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endCreateTime,

        @ApiParam(value = "个人证书类别(1:注册类；2：非注册类)", name = "type", defaultValue = "1")
        @RequestParam(value = "type", defaultValue = "1") Integer type,

        @ApiParam(value = "人才姓名", name = "personnelName")
        @RequestParam(value = "personnelName", required = false) String personnelName,

        @ApiParam(value = "文件名字（全名）", name = "certificateDataName")
        @RequestParam(value = "certificateDataName", required = false) String certificateDataName,

        @ApiParam(value = "上传的文件类型（1：zip）", name = "certificateDataType")
        @RequestParam(value = "certificateDataType", required = false) String certificateDataType,

        @ApiParam(value = "职称类型", name = "titleType")
        @RequestParam(value = "titleType", required = false) String titleType,

        @ApiParam(value = "限制地区 code", name = "restrictedAreasCode")
        @RequestParam(value = "restrictedAreasCode", required = false) String restrictedAreasCode,

        @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {

        UserCertificateDTO dto = UserCertificateDTO.builder()
            .companyName(companyName)
            .acceptCertificateUserName(acceptCertificateUserName)
            .personnelName(personnelName)
            .startTitleTime(startTitleTime)
            .endTitleTime(endTitleTime)
            .personnelTel(personnelTel)
            .titleMajor(titleMajor)
            .titleMajor(titleMajor)
            .certificateTypeName(certificateTypeName)
            .graduationMajor(graduationMajor)
            .startGraduationTime(startGraduationTime)
            .endGraduationTime(endGraduationTime)
            .qualification(qualification)
            .category(category)
            .idCard(idCard)
            .certificateBelongingPlace(certificateBelongingPlace)
            .restrictedAreas(restrictedAreas)
            .titleNumber(titleNumber)
            .startCreateTime(startCreateTime)
            .endCreateTime(endCreateTime)
            .likeTitleMajor(likeTitleMajor)
            .placeCode(placeCode)
            .certificateDataName(certificateDataName)
            .certificateDataType(certificateDataType)
            .type(type)
            .titleType(titleType)
            .restrictedAreasCode(restrictedAreasCode)
            .restrictedAreass(restrictedAreass)
            .build();
        Page<UserCertificateDTO> pageList = userCertificateService.list(dto, pageSize,pageNum);
        return CommonResult.success(CommonPage.restPage(pageList));
    }

    @ApiOperation("添加、修改证书(form-data 传参)")
    @RequestMapping(value = "/addOrUpt", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult addOrUpt(
        @ApiParam(value = "数据id，修改时必传",name = "id")
        @RequestParam(value = "id", required = false) Long id,
        @ApiParam(value = "公司名称",name = "companyName")
        @RequestParam(value = "companyName", required = false) String companyName,
        @ApiParam(value = "收证人", name = "acceptCertificateUserName")
        @RequestParam(value = "acceptCertificateUserName", required = false) String acceptCertificateUserName,
        @ApiParam(value = "职称年份（yyyy-MM-dd）", name = "titleTime")
        @RequestParam(value = "titleTime", required = false)  @DateTimeFormat(pattern = "yyyy-MM-dd") Date titleTime,
        @ApiParam(value = "人才电话", name = "personnelTel")
        @RequestParam(value = "personnelTel", required = false) String personnelTel,
        @ApiParam(value = "职称专业", name = "titleMajor")
        @RequestParam(value = "titleMajor", required = false) String titleMajor,
        @ApiParam(value = "职称类型", name = "titleType")
        @RequestParam(value = "titleType", required = false) String titleType,
        @ApiParam(value = "证书类型", name = "certificateTypeName")
        @RequestParam(value = "certificateTypeName", required = false) String certificateTypeName,
        @ApiParam(value = "毕业专业", name = "graduationMajor")
        @RequestParam(value = "graduationMajor", required = false) String graduationMajor,
        @ApiParam(value = "毕业年份（yyyy-MM-dd）", name = "graduationTime")
        @RequestParam(value = "graduationTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date graduationTime,
        @ApiParam(value = "学历（1：专科，2：本科 ，3：硕士）", name = "qualification")
        @RequestParam(value = "qualification", required = false) String qualification,
        @ApiParam(value = "电子、纸质（1：电子，2：纸质）", name = "category")
        @RequestParam(value = "category", required = false) String category,
        @ApiParam(value = "身份证号", name = "idCard")
        @RequestParam(value = "idCard", required = false) String idCard,
        @ApiParam(value = "证书归属地", name = "certificateBelongingPlace")
        @RequestParam(value = "certificateBelongingPlace", required = false) String certificateBelongingPlace,
        @ApiParam(value = "证书归属地 code", name = "placeCode")
        @RequestParam(value = "placeCode", required = false) String placeCode,
        @ApiParam(value = "限制地区", name = "restrictedAreas")
        @RequestParam(value = "restrictedAreas", required = false) String restrictedAreas,
        @ApiParam(value = "限制地区 code", name = "restrictedAreasCode")
        @RequestParam(value = "restrictedAreasCode", required = false) String restrictedAreasCode,
        @ApiParam(value = "职称编号", name = "titleNumber")
        @RequestParam(value = "titleNumber", required = false) String titleNumber,
        @ApiParam(value = "个人证书类别(1:注册类；2：非注册类)", name = "type", defaultValue = "1")
        @RequestParam(value = "type", defaultValue = "1") Integer type,
        @ApiParam(value = "人才姓名", name = "personnelName")
        @RequestParam(value = "personnelName", required = false) String personnelName,
        @ApiParam(value = "价格资质", name = "price")
        //@Pattern(regexp = "^-?\\d+(\\.\\d+)?$", message = "价格资质需要输入数字类型")
        @RequestParam(value = "price", required = false) String price,
        @ApiParam(value = "备注", name = "remark")
        @RequestParam(value = "remark", required = false) String remark,
        @ApiParam(value = "上传文件", name = "certificateFile")
        @RequestParam(value = "certificateFile", required = false)  MultipartFile certificateFile) {
//        if(StringUtil.isNotEmpty(price) && !VerificationUtil.isNumeric(price)){
//            return CommonResult.failed("价格资质不是数字类型");
//        }

        UserCertificateDTO dto = UserCertificateDTO.builder()
            .companyName(companyName)
            .acceptCertificateUserName(acceptCertificateUserName)
            .personnelName(personnelName)
            .personnelTel(personnelTel)
            .titleMajor(titleMajor)
            .titleMajor(titleMajor)
            .certificateTypeName(certificateTypeName)
            .graduationMajor(graduationMajor)
            .qualification(qualification)
            .category(category)
            .idCard(idCard)
            .certificateBelongingPlace(certificateBelongingPlace)
            .restrictedAreas(restrictedAreas)
            .titleNumber(titleNumber)
            .type(type)
            .id(id)
            .certificateFile(certificateFile)
            .placeCode(placeCode)
            .titleType(titleType)
            .price(price)
            .remark(remark)
            .titleTime(titleTime)
            .graduationTime(graduationTime)
            .restrictedAreasCode(restrictedAreasCode)
            .build();
        boolean success = userCertificateService.addOrUpt(dto);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }


    @ApiOperation("删除")
    @RequestMapping(value = "/updateDel/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult updateDel(
        @ApiParam(value = "数据id", name = "id")
        @PathVariable Long id) {
        boolean success = userCertificateService.updateDel(id);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @ApiOperation("下载 zip 文件")
    @GetMapping("/exportBinaryData/{id}")
    public ResponseEntity<byte[]> exportBinaryData(
        @ApiParam(value = "数据id", name = "id")
        @PathVariable Long id) throws IOException {

        UserCertificate certificate = userCertificateService.getFileInfo(id);
        if(certificate == null || certificate.getCertificateData() == null){
            return ResponseEntity.noContent().build();
        }
        // 从数据库获取二进制数据
        byte[] certificateData = certificate.getCertificateData();

        String fileName = certificate.getCertificateDataName();
        String encodedFileName = UriUtils.encode(fileName, StandardCharsets.UTF_8); // 编码文件名

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", encodedFileName);
        // 直接返回数据库中存储的ZIP文件内容
        return ResponseEntity.ok()
            .headers(headers)
            .body(certificateData);
    }

}

